package edu.cuit.zhuyimeng.flight.job;

import com.alicp.jetcache.Cache;
import com.baomidou.dynamic.datasource.annotation.Master;
import edu.cuit.zhuyimeng.flight.controller.vo.FlightInfoVO;
import edu.cuit.zhuyimeng.flight.service.IFlightManagerService;
import edu.cuit.zhuyimeng.flight.service.IFlightQueryService;
import edu.cuit.zhuyimeng.framework.common.system.enums.FlightStatus;
import edu.cuit.zhuyimeng.framework.common.system.enums.SysConstants;
import edu.cuit.zhuyimeng.framework.workflow.util.ProcessUtils;
import edu.cuit.zhuyimeng.ticket.api.controller.TicketDispatchApiController;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Component;
import tech.powerjob.worker.core.processor.ProcessResult;
import tech.powerjob.worker.core.processor.TaskContext;
import tech.powerjob.worker.core.processor.sdk.BasicProcessor;

import java.util.List;
import java.util.Map;

/**
 * 开发订票调度任务（调用订票模块接口）
 */
@Component("releaseTicketProcessor")
@Slf4j
@RequiredArgsConstructor
public class ReleaseTicketProcessor implements BasicProcessor {

    private final IFlightQueryService flightQueryService;

    private final TicketDispatchApiController ticketDispatchApiController;

    private final Cache<Long, FlightInfoVO> flightInfoCache;
    private final Cache<String, List<Long>> specificFlightInfoCache;

    private final TaskService taskService;
    private final RuntimeService runtimeService;

    @Override
    @Master
    public ProcessResult process(TaskContext taskContext) throws Exception {
        FlightInfoVO flightInfoVO = flightQueryService.queryOneFlight(Long.valueOf(taskContext.getJobParams()));
        log.info("航班 " + flightInfoVO.getNumber() + " 开放订票调度任务开始");
        ticketDispatchApiController.openFlightBooking(flightInfoVO.getId());
        Task task = taskService.createTaskQuery().processInstanceBusinessKey(String.valueOf(flightInfoVO.getId())).singleResult();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(String.valueOf(flightInfoVO.getId())).includeProcessVariables().singleResult();
        Map<String, Object> processVariables = processInstance.getProcessVariables();
        processVariables.put(SysConstants.STATUS,FlightStatus.BOOKING.getType());
        taskService.complete(task.getId());
        ProcessUtils.setVariables(processInstance,processVariables);
        flightInfoCache.remove(flightInfoVO.getId());
        specificFlightInfoCache.remove(flightInfoVO.getCacheKey());
        log.info("航班 " + flightInfoVO.getNumber() + " 开放订票调度任务结束，成功发送请求");
        return new ProcessResult(true,"成功");
    }
}
